<?php


namespace app\api\controller\v1;


use app\api\exception\BaseException;
use app\api\validate\ClassScene;
use app\api\validate\GoodsScene;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Request;

/**
 * Class Goods
 * @package app\api\controller\v1
 * 产品
 */
class Goods extends BaseException
{
    /**
     * 不需要登录方法
     */
    protected $noAuth = [];

    /**
     * 获取产品列表
     */
    public function getGoodsList()
    {
        $data = Request::param();
        $search = [

        ];
        if (isset($data["sort"]) && $data["sort"] == "+id") {
            $order = ["is_top" => "desc","id" => "asc"];
        } else {
            $order = ["is_top" => "desc","id" => "desc"];
        }

        /**
         * 单一模糊查询开始
         */
        //产品名称模糊查询
        if (isset($data["goods_name"]) && !empty($data["goods_name"])) {
            $search[] = ["goods_name", "like", "%" . $data["goods_name"] . "%"];
        }
        //产品品牌模糊查询
        if (isset($data["goods_brand"]) && !empty($data["goods_brand"])) {
            $search[] = ["goods_brand", "like", "%" . $data["goods_brand"] . "%"];
        }

        /**
         * 单一模糊查询结束
         */
        /**
         *多条件查询开始
         */
        //数据状态筛选查询
        //  if (isset($data["data_state"]) && $data["data_state"] != '') {
        array_push($search, ["data_state", "=", 1]);
        //}
        //是否置顶
        if (isset($data["is_top"]) && $data["is_top"] != '') {
            array_push($search, ["is_top", "=", $data["is_top"]]);
        }
        //分类筛选查询
        if (isset($data["goods_class"]) && $data["goods_class"] != '') {
            array_push($search, ["goods_class", "=", $data["goods_class"]]);
        }
        //仓库筛选查询
        if (isset($data["depot_id"]) && $data["depot_id"] != '') {
            array_push($search, ["depot_id", "=", $data["depot_id"]]);
        }
        //上架状态筛选查询
        if (isset($data["status"]) && $data["status"] != '') {
            array_push($search, ["status", "=", $data["status"]]);
        }
        if($this->user_type >2){
            array_push($search, ["data_state", "=", 1]);
        }
        $goodslist = Db::name("goods")->where($search)->order($order)->page($data["page"], $data["limit"])->select()->toArray();
        $count = Db::name("goods")->where($search)->count();
        foreach ($goodslist as $key => $value) {
            $goodslist[$key]["imgs"] = explode(",", $goodslist[$key]["goods_imgs"]);
            $goodsImgsArray = explode(",", $goodslist[$key]["goods_imgs"]);
            $goodsColorArray = explode(",", $goodslist[$key]["goods_color"]);
            $goodsSizeArray = explode(",", $goodslist[$key]["goods_size"]);

            for ($index = 0; $index < count($goodsImgsArray); $index++) {
                $goodsImgsArray[$index] = "http://" . $_SERVER['HTTP_HOST'] . $goodsImgsArray[$index];
            }
            $goodslist[$key]["goods_color"] = $goodsColorArray;
            $goodslist[$key]["num"] = 1;
            $goodslist[$key]["goods_size"] = $goodsSizeArray;
            $goodslist[$key]["goods_imgs"] = $goodsImgsArray;

            $goodslist[$key]["depot_id"] = Db::name("goods_depot")->where(["id" => $value["depot_id"]])->field("id,name")->find();
            $goodslist[$key]["goods_class"] = Db::name("goods_class")->where(["id" => $value["goods_class"]])->field("id,name")->find();
            $goodslist[$key]["goods_brand"] = Db::name("brand")->where(["id" => $value["goods_brand"]])->field("id,name")->find();
        }
        $list = [
            "total" => $count,
            "page" => $data["page"],
            "limit" => $data["limit"],
            "list" => $goodslist,

        ];
        return self::Success($list, '获取成功', 200);
    }

    public function createGoodsInfo()
    {
        $request = Request::param();

        $insertData = [
            "goods_name" => isset($request["goods_name"]) ? $request["goods_name"] : "",
            "goods_imgs" => isset($request["goods_imgs"]) ? $request["goods_imgs"] : "",
            "goods_color" => isset($request["goods_color"]) ? $request["goods_color"] : "",
            "goods_size" => isset($request["goods_size"]) ? $request["goods_size"] : "",
            "retail_price" => isset($request["retail_price"]) ? number_format($request["retail_price"], 2) : 0,
            "goods_class" => isset($request["goods_class"]) ? $request["goods_class"] : 0,
            "goods_brand" => isset($request["goods_brand"]) ? $request["goods_brand"] : 0,
            "depot_id" => isset($request["depot_id"]) ? $request["depot_id"] : 0,
            "is_top" => 0,
            "status" => 1,
            'create_time' => date("Y-m-d H:i:s", time()),
            'update_time' => date("Y-m-d H:i:s", time()),
            'create_time_d' => time(),
            'data_state' => 1
        ];
        $result = Db::name("goods")->insert($insertData);
        if ($result) {
            return self::Success(null, "添加成功", 200);
        } else {
            return self::Error(null, '添加失败', 10002);
        }
    }
    /**
     * 新增产品信息
     */
    public function addGoodsInfo()
    {
        $request = Request::param();
        try {
            validate(GoodsScene::class)
                ->scene('add')
                ->check($request);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return self::Error(null, $e->getError(), 404);
        }
        $insertData = [
            "goods_name" => isset($request["goods_name"]) ? $request["goods_name"] : "",
            "goods_imgs" => isset($request["goods_imgs"]) ? $request["goods_imgs"] : "",
            "goods_color" => isset($request["goods_color"]) ? $request["goods_color"] : "",
            "goods_size" => isset($request["goods_size"]) ? $request["goods_size"] : "",
            "cost_price" => isset($request["cost_price"]) ? number_format($request["cost_price"], 2) : 0,
            "agency_price" => isset($request["agency_price"]) ? number_format($request["agency_price"], 2) : 0,
            "retail_price" => isset($request["retail_price"]) ? number_format($request["retail_price"], 2) : 0,
            "is_top" => 0,
            "goods_class" => isset($request["goods_class"]) ? $request["goods_class"] : 0,
            "goods_brand" => isset($request["goods_brand"]) ? $request["goods_brand"] : 0,
            "status" => 1,
            "goods_weight" => isset($request["goods_weight"]) ? $request["goods_weight"] : '',
            "depot_id" => isset($request["depot_id"]) ? $request["depot_id"] : 0,
            "shelf_time" => date("Y-m-d H:i:s", time()),
            'create_time' => date("Y-m-d H:i:s", time()),
            'update_time' => date("Y-m-d H:i:s", time()),
            'create_time_d' => time(),
            'data_state' => 1
        ];
        $result = Db::name("goods")->insert($insertData);
        if ($result) {
            return self::Success(null, "添加成功", 200);
        } else {
            return self::Error(null, '添加失败', 10002);
        }
    }


    public function batchDelete()
    {
        $request = Request::param();
        $ids = explode(",", $request["ids"]);
        if (count($ids) != 0) {
            for ($i = 0; $i < count($ids); $i++) {
                $updateData = [
                    "data_state" => 0,
                    "update_time" => date("Y-m-d H:i:s", time()),
                ];
                Db::name("goods")->where(["id" => $ids[$i]])->update($updateData);
            }
        }
        return self::Success(null, "删除成功", 200);
    }
    /**
     *
     * 更新产品信息
     */
    public function updateGoodsInfo()
    {
        $request = Request::param();
        try {
            validate(GoodsScene::class)
                ->scene('update')
                ->check($request);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return self::Error(null, $e->getError(), 404);
        }
        $updateData = [
            "goods_name" => isset($request["goods_name"]) ? $request["goods_name"] : "",
            "goods_imgs" => isset($request["goods_imgs"]) ? $request["goods_imgs"] : "",
            "goods_color" => isset($request["goods_color"]) ? $request["goods_color"] : "",
            "goods_size" => isset($request["goods_size"]) ? $request["goods_size"] : "",
            "cost_price" => isset($request["cost_price"]) ? number_format($request["cost_price"], 2) : 0,
            "agency_price" => isset($request["agency_price"]) ? number_format($request["agency_price"], 2) : 0,
            "retail_price" => isset($request["retail_price"]) ? number_format($request["retail_price"], 2) : 0,
            "goods_class" => isset($request["goods_class"]) ? $request["goods_class"] : 0,
            "goods_brand" => isset($request["goods_brand"]) ? $request["goods_brand"] : 0,
            "goods_weight" => isset($request["goods_weight"]) ? $request["goods_weight"] : '',
            "depot_id" => isset($request["depot_id"]) ? $request["depot_id"] : 0,
            "is_top" => isset($request["is_top"]) ? $request["is_top"] : 0,
            "status" => isset($request["status"]) ? $request["status"] : 0,
            'update_time' => date("Y-m-d H:i:s", time()),
        ];
        $result = Db::name("goods")->where(["id" => $request["id"]])->update($updateData);
        if ($result) {
            return self::Success(null, "更新成功", 200);
        } else {
            return self::Error(null, '更新成功', 10002);
        }
    }

    /**
     *
     * 批量删除产品
     */
    public function batchUpdateGoodsState()
    {
        $request = Request::param();
        try {
            validate(GoodsScene::class)
                ->scene('update_state')
                ->check($request);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return self::Error(null, $e->getError(), 404);
        }
        $updateData = [
            "data_state" => $request["data_state"],
            "update_time" => date("Y-m-d H:i:s", time()),
        ];
        $check = Db::name("goods")->where(["id" => $request["id"]])->find();
        if ($check) {
            $result = Db::name("goods")->where(["id" => $request["id"]])->update($updateData);
            if ($result) {
                return self::Success(null, "操作成功", 200);
            } else {
                return self::Error(null, '操作失败', 10002);
            }
        } else {
            return self::Error(null, '商品不存在', 10002);
        }
    }

    /**
     *
     * 更改产品上架下架
     * 上架1 下架0
     * status
     */
    public function updateGoodsStatus()
    {
        $request = Request::param();
        try {
            validate(GoodsScene::class)
                ->scene('update_status')
                ->check($request);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return self::Error(null, $e->getError(), 404);
        }
        if ($request["status"] == 1) {
            $updateData = [
                "status" => $request["status"],
                "shelf_time" => date("Y-m-d H:i:s", time()),
                "update_time" => date("Y-m-d H:i:s", time()),
            ];
        }else{
            $updateData = [
                "status" => $request["status"],
                "update_time" => date("Y-m-d H:i:s", time()),
            ];
        }

        $check = Db::name("goods")->where(["id" => $request["id"]])->find();
        if ($check) {
            $result = Db::name("goods")->where(["id" => $request["id"]])->update($updateData);
            if ($result) {
                return self::Success(null, "操作成功", 200);
            } else {
                return self::Error(null, '操作失败', 10002);
            }
        } else {
            return self::Error(null, '商品不存在', 10002);
        }
    }

    /**
     *
     * 更改产品是否置顶
     * 置顶1 未指定0
     * is_top
     */
    public function updateGoodsIsTop()
    {
        $request = Request::param();
        try {
            validate(GoodsScene::class)
                ->scene('update_is_top')
                ->check($request);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return self::Error(null, $e->getError(), 404);
        }
        $updateData = [
            "is_top" => $request["is_top"],
            "update_time" => date("Y-m-d H:i:s", time()),
        ];
        $check = Db::name("goods")->where(["id" => $request["id"]])->find();
        if ($check) {
            $result = Db::name("goods")->where(["id" => $request["id"]])->update($updateData);
            if ($result) {
                return self::Success(null, "操作成功", 200);
            } else {
                return self::Error(null, '操作失败', 10002);
            }
        } else {
            return self::Error(null, '商品不存在', 10002);
        }
    }


}